package com.java.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.service.ShopProductService;
import com.java.util.CommonUtil;
import com.java.vo.PointRuleVo;
import com.java.vo.ShopProduct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品模块
 */
@Controller
@RequestMapping("/shopProduct")
public class QueryShopProductController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ShopProductService shopProductService;

    private static final String RETURN_FLAG = "return_flag";

    private static final String RETURN_MSG = "return_msg";

    private String toJsonStr(Object obj) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));// date类型转换格式
        mapper.setSerializationInclusion(Include.ALWAYS);// 设置为always 序列化时
                                                         // 保留null属性

        return mapper.writeValueAsString(obj).replace(":\"\"", ":\"-\"")// 将空串转换为"-"
                .replace(":null", ":\"-\"");// 将null转换为"-"
    }

    @RequestMapping(value = "/setShelf", method = RequestMethod.POST)
    @ResponseBody
    public void setShelf(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            Integer id = jsonData.getInteger("id");
            Integer isUp = jsonData.getInteger("isUp");

            if (id == null || isUp == null) {
                throw new Exception("参数有误");
            }

            if (!shopProductService.setShelf(id, isUp)) {
                throw new Exception("保存失败");
            }

            jsonMap.put(RETURN_FLAG, true);
            jsonMap.put(RETURN_MSG, "保存成功");
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/activeList", method = RequestMethod.POST)
    @ResponseBody
    public void getProductActiveList(@RequestParam String Jdata, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());

            List<ShopProduct> shopProducts = shopProductService.getProductActiveList();
            if (shopProducts != null) {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put("shopProducts", shopProducts);
            } else {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put("shopProducts", null);
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public void getProductList(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            String name = jsonData.getString("name");
            Integer isSend = jsonData.getInteger("isSend");
            String label = jsonData.getString("label");
            String content = jsonData.getString("content");
            Integer page = jsonData.getInteger("page");
            String id = jsonData.getString("id");

            if (!StringUtils.isEmpty(id)) {
                ShopProduct productDetailById = shopProductService.getProductDetailById(Integer.valueOf(id));
                shopProductService.formatProductLimit(productDetailById.getShopProductLimit());
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put("shopProducts", productDetailById);
                return;
            }

            List<ShopProduct> shopProducts = shopProductService.getProductList(name, isSend, label, content, page);
            Integer Cnt = shopProductService.getProductDetailCnt(name, isSend, label, content, page);
            if (shopProducts != null) {
                // String jsonarray = JSONArray.toJSONString(shopProducts);
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put("shopProducts", shopProducts);
                jsonMap.put("cnt", Cnt);
            } else {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put("shopProducts", null);
                jsonMap.put("cnt", Cnt);
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/addShopProduct", method = RequestMethod.POST)
    @ResponseBody
    public void addShopProduct(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            String shopProduct = jsonData.getString("ShopProduct");
            ShopProduct sp = JSONObject.parseObject(shopProduct, ShopProduct.class);
            if (sp == null) {
                jsonMap.put(RETURN_FLAG, false);
                jsonMap.put(RETURN_MSG, "传入对象转换后为空");
            } else {
                sp.setIsUp(0);
                Integer id = shopProductService.insertShopProduct(sp);
                if (id > 0) {
                    jsonMap.put(RETURN_FLAG, true);
                    jsonMap.put(RETURN_MSG, "操作成功");
                    jsonMap.put("id", id);
                } else {
                    jsonMap.put(RETURN_FLAG, false);
                    jsonMap.put(RETURN_MSG, "操作失败");
                }
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/updateShopProduct", method = RequestMethod.POST)
    @ResponseBody
    public void updateShopProduct(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            String shopProduct = jsonData.getString("ShopProduct");
            ShopProduct sp = JSONObject.parseObject(shopProduct, ShopProduct.class);
            if (sp == null) {
                jsonMap.put(RETURN_FLAG, false);
                jsonMap.put(RETURN_MSG, "传入对象转换后为空");
            } else {
                ShopProduct spdb = shopProductService.getProductDetailById(sp.getId());
                spdb.setName(sp.getName());
                spdb.setPriceType(sp.getPriceType());
                spdb.setPriceCash(sp.getPriceCash());
                spdb.setPricePoint(sp.getPricePoint());
                spdb.setIsSend(sp.getIsSend());
                spdb.setShowSaledNum(sp.getShowSaledNum());
                spdb.setLabel(sp.getLabel());
                spdb.setWeight(sp.getWeight());
                spdb.setInventoryNum(sp.getInventoryNum());
                spdb.setFictitiousType(sp.getFictitiousType());
                spdb.setShopProductLimit(sp.getShopProductLimit());
                spdb.setPriceMarket(sp.getPriceMarket());
                spdb.setTicketSystemId(sp.getTicketSystemId());
                boolean flag = shopProductService.updateShopProduct(spdb);
                if (flag) {
                    jsonMap.put(RETURN_FLAG, true);
                    jsonMap.put(RETURN_MSG, "操作成功");
                } else {
                    jsonMap.put(RETURN_FLAG, false);
                    jsonMap.put(RETURN_MSG, "操作失败");
                }
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/updateContent", method = RequestMethod.POST)
    @ResponseBody
    public void updateContent(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            Integer id = jsonData.getInteger("id");
            String content = jsonData.getString("content");

            ShopProduct shopProduct = shopProductService.getProductDetailById(id);
            if (null == shopProduct) {
                throw new Exception("未找到商品");
            }
            shopProduct.setContent(content);
            shopProduct.setContentType(0);
            if (shopProductService.updateShopProduct(shopProduct)) {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put(RETURN_MSG, "操作成功");
                return;
            } else {
                throw new Exception("保存失败");
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/saveImage", method = RequestMethod.POST)
    @ResponseBody
    public void saveImage(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        CommonUtil.setResponseParams(response);
        com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
        com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
        Integer id = jsonData.getInteger("id");
        String type = jsonData.getString("type");
        String filePath = jsonData.getString("filePath");

        HashMap<String, Object> jsonMap = new HashMap<String, Object>();

        try {
            ShopProduct shopProduct = shopProductService.getProductDetailById(id);
            if (null == shopProduct) {
                throw new Exception("未找到商品");
            }

            if ("1".equals(type)) {
                if ("-".equals(shopProduct.getContent())) {
                    shopProduct.setContent(fomatImgPath(filePath));
                } else {
                    shopProduct.setContent(shopProduct.getContent() + fomatImgPath(filePath));
                }
                shopProduct.setContentType(1);
            }
            if ("2".equals(type)) {
                shopProduct.setImgBigUrl(filePath);
                /*
                 * if("-".equals(shopProduct.getImgBigUrl())){
                 * shopProduct.setImgBigUrl(fomatImgPath(filePath)); }else{
                 * shopProduct.setImgBigUrl(shopProduct.getImgBigUrl() +
                 * fomatImgPath(filePath)); }
                 */}
            if ("3".equals(type)) {
                shopProduct.setImgSmallUrl(filePath);
                /*
                 * if("-".equals(shopProduct.getImgSmallUrl())){
                 * shopProduct.setImgSmallUrl(fomatImgPath(filePath)); }else{
                 * shopProduct.setImgSmallUrl(shopProduct.getImgSmallUrl() +
                 * fomatImgPath(filePath)); }
                 * 
                 */}

            if (shopProductService.updateShopProduct(shopProduct)) {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put(RETURN_MSG, "操作成功");
                return;
            } else {
                throw new Exception("保存失败");
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    @RequestMapping(value = "/ticketSystemDict", method = RequestMethod.POST)
    public void ticketSystemDict(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            CommonUtil.setResponseParams(response);
            // List<Map<String, Object>> ticketSystemDict =
            // ticketSystemService.ticketSystemDict();
            // jsonMap.put("data", ticketSystemDict);
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }

    private String fomatImgPath(String path) {
        return "<img class=\"img\" src=\"" + path + "\">";
    }

    @RequestMapping(value = "/delImage", method = RequestMethod.POST)
    @ResponseBody
    public void delImage(@RequestParam String Jdata, HttpServletRequest req, HttpServletResponse response)
            throws IOException {

        CommonUtil.setResponseParams(response);
        com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
        com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
        Integer id = jsonData.getInteger("id");
        String type = jsonData.getString("type");
        String filePath = jsonData.getString("filePath");

        HashMap<String, Object> jsonMap = new HashMap<String, Object>();

        try {
            ShopProduct shopProduct = shopProductService.getProductDetailById(id);
            if (null == shopProduct) {
                throw new Exception("未找到商品");
            }

            if ("1".equals(type)) {
                String content = shopProduct.getContent();
                content = content.replace(fomatImgPath(filePath), "");
                shopProduct.setContent(content);
            }
            if ("2".equals(type)) {
                shopProduct.setImgBigUrl("");
            }
            if ("3".equals(type)) {
                shopProduct.setImgSmallUrl("");
            }

            if (shopProductService.updateShopProduct(shopProduct)) {
                jsonMap.put(RETURN_FLAG, true);
                jsonMap.put(RETURN_MSG, "操作成功");
                return;
            } else {
                throw new Exception("保存失败");
            }
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }
    }

    @RequestMapping(value = "/rules", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findRules() {
        Map<String, Object> jsonMap = new HashMap<>();
        try {
            List<PointRuleVo> allPointRules = shopProductService.findAllPointRules();
            jsonMap.put("data", allPointRules);
        } catch (Exception e) {
            logger.error("findAllPointRules error", e);
        }
        return jsonMap;
    }

    @RequestMapping(value = "/rulesObj", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findRulesObj() {
        Map<String, Object> jsonMap = new HashMap<>();
        try {
            List<PointRuleVo> allPointRules = shopProductService.findAllPointRules();
            Map<Integer, String> collect = allPointRules.stream().collect(Collectors.toMap(rule -> rule.getId(), rule -> rule.getRuleName()));
            jsonMap.put("data", collect);
        } catch (Exception e) {
            logger.error("findAllPointRules error", e);
        }
        return jsonMap;
    }
}
